package jfuzzyprincepless.negotiation;

import jfuzzyprincepless.agents.INegotiatingAgent;
import jfuzzyprincepless.negotiation.services.IAgentsListService;
import jfuzzyprincepless.negotiation.services.impl.AgentsListService;

import java.util.*;

public class NegotiationUtils {
	private NegotiationUtils() {}

	public static void onNegotiationStart(
		List<INegotiatingAgent> agents,
		INegotiationContext context
	) {
		for (INegotiatingAgent agent : new ArrayList<INegotiatingAgent>(agents)) {
			agent.onNegotiationStart(context);
		}
	}

	public static void defaultNegotiationIteration(
		INegotiationContext context
	) {
		IAgentsListService agList =
			context.getService(IAgentsListService.class);

		onNegotiationStart(agList.getAgentsList(), context);

		agList = context.getService(IAgentsListService.class);

		Set<INegotiatingAgent> negAgents =
			new LinkedHashSet<INegotiatingAgent>(agList.getAgentsList());

		while (!negAgents.isEmpty()) {
			for (
				Iterator<INegotiatingAgent> it = negAgents.iterator();
				it.hasNext();
			) {
				INegotiatingAgent agent = it.next();
				boolean isAlive = agent.negotiate(context);
				if (!isAlive) {
					it.remove();
				}
			}
		}
	}

	public static void defaultNegotiationIteration(
		List<INegotiatingAgent> agents,
		INegotiationContext context
	) {
		AgentsListService agList =
			new AgentsListService(agents);
		context.registerService(agList);
		defaultNegotiationIteration(context);
	}
}
